package com.hz.friends.fragment;


import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.avos.avoscloud.AVUser;
import com.hz.friends.activity.ChangePwdActivity;
import com.hz.friends.activity.R;
import com.hz.friends.activity.SelectLanguageActivity;
import com.hz.friends.activity.SystemMessageActivity;
import com.hz.friends.activity.UserInfosActivity;
import com.hz.friends.activity.WelcomeAcitivity;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.global.Global;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;

public class SetupFragment extends BaseFragment implements OnClickListener{
	private ImageView imv_heard;
	private LinearLayout layout_heard;
	private LinearLayout layout_systemmsg;
	private TextView txv_name;
	private AQuery aq;
	private final int Language_REQUEST = 12; // 语言选择页面跳转request
	private TextView txv_language;
	private TextView txv_cachenum;


	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_setup, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		init();
		initViews();
		initEvents();
	}

	@Override
	protected void init() {
		aq = new AQuery(getActivity());
	}

	@Override
	protected void initViews() {
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_left.setVisibility(View.INVISIBLE);
		imbtn_bar_right.setVisibility(View.INVISIBLE);
		imbtn_bar_title.setText("Set up");
		
		layout_systemmsg = (LinearLayout)findViewById(R.id.layout_systemmsg);
		layout_heard = (LinearLayout)findViewById(R.id.layout_heard);
		imv_heard = (ImageView)findViewById(R.id.imv_heard);
		txv_name = (TextView)findViewById(R.id.txv_name);
		
		LinearLayout layout_changepwd = (LinearLayout)findViewById(R.id.layout_changepwd); //修改密码
		LinearLayout layout_selectlanguage = (LinearLayout)findViewById(R.id.layout_selectlanguage); //语言选择
		 txv_language = (TextView)findViewById(R.id.txv_language); //语言 
		LinearLayout layout_gold = (LinearLayout)findViewById(R.id.layout_gold); //充值
		Button btn_logout = (Button)findViewById(R.id.btn_logout); //充值
		LinearLayout layout_cache = (LinearLayout)findViewById(R.id.layout_cache); //缓存
		 txv_cachenum = (TextView)findViewById(R.id.txv_cachenum);  //缓存
		layout_heard.setOnClickListener(this);
		layout_systemmsg.setOnClickListener(this);
		layout_changepwd.setOnClickListener(this);
		layout_selectlanguage.setOnClickListener(this);
		layout_gold.setOnClickListener(this);
		btn_logout.setOnClickListener(this);
		layout_cache.setOnClickListener(this);
		
		AVUser user = AVUser.getCurrentUser();
		String heardurl = user.getString("headViewURL");
		String nickname = user.getString("nickname");
		String signature = user.getString("signature");
		
		final int width = DensityUtil.dip2px(getActivity(), 69);
		final int stroke = DensityUtil.dip2px(getActivity(), 1);
		Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
		Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
				getActivity(), crclebitmap, width, stroke, "#eeeeee");
		 imv_heard.setImageBitmap(crclestrokebitmap);

		aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
			@Override
			public void callback(String url, Bitmap bitmap,
					AjaxStatus status) {
				Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(getActivity(),
						bitmap, width, stroke, "#eeeeee");
				 imv_heard.setImageBitmap(mbitmap);
			}
		});
		txv_name.setText(nickname);
		getCacheNum();
	}
	@Override
	public void initDatas() {
	}
	@Override
	protected void setViews() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void initEvents() {
		// TODO Auto-generated method stub
		
	}
      
	private TextView inputTextView = null;
	@Override
	public void onClick(View v) {
            switch (v.getId()) {
			case R.id.layout_heard:
			((CustomApplication)getActivity().getApplication()).user = AVUser.getCurrentUser();
				startActivity(UserInfosActivity.class);
				break;
			case R.id.layout_systemmsg:
				startActivity(SystemMessageActivity.class);
				break;
			case R.id.layout_selectlanguage://选择语言
				Intent languageintent = new Intent(getActivity(),SelectLanguageActivity.class);
				languageintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(languageintent, Language_REQUEST);
				inputTextView = txv_language;
				break;
			case R.id.layout_changepwd:
				Intent changepwdintent = new Intent(getActivity(),ChangePwdActivity.class);
				changepwdintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(changepwdintent);
				break;
			case R.id.layout_gold:
				showToast("充值成功");
				break;
			case R.id.btn_logout://登出
				logout();
				break;
			case R.id.layout_cache://缓存
				clearCache();
				break;
			default:
				break;
			}		
	}
	
	
   private void logout(){
	   new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("是否注销登陆?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
             			ALUserEngine.defauleEngine().logOut();
             			Intent intent = new Intent(getActivity(), WelcomeAcitivity.class);
             			startActivity(intent);
             			getActivity().finish();
		}
	}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			
		}
	}).create().show();
   }
   
   private void clearCache(){

	   new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("是否注清除缓存").setPositiveButton("确定", new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			try {
				Toast.makeText(getActivity(), "正在删除...", Toast.LENGTH_LONG).show();
				String cachepath = Environment.getExternalStorageDirectory()+"/"+Global.productName;
				deleteFolderFile(cachepath, true);
				showToast("缓存已清空");
				txv_cachenum.setText("");
			} catch (IOException e) {
				e.printStackTrace();
				showToast("清空缓存失败");

			}
		}
	}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			
		}
	}).create().show();
   
   }
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if ( requestCode == Language_REQUEST && data != null) {// 输入\语言
			String text = data.getStringExtra("text");
			boolean ischange = data.getBooleanExtra("ischange", false);
			if (inputTextView != null && ischange)
				inputTextView.setText(text);
		}
	}
	public void onmActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;
		if ( requestCode == Language_REQUEST) {// 输入\语言
			String text = data.getStringExtra("text");
			boolean ischange = data.getBooleanExtra("ischange", false);
			if (inputTextView != null && ischange)
				inputTextView.setText(text);
		}

	}
	
	private void getCacheNum() {
		if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
				.getExternalStorageState()))
			return;
		String cachepath = Environment.getExternalStorageDirectory()+"/"+Global.productName;
		File cachefiledir = new File(cachepath);
		if (!cachefiledir.exists())
			return;

		try {
			String num = setFileSize(getFolderSize(cachefiledir));
			txv_cachenum.setText(num);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	/**
	 * 获取文件夹大小
	 * 
	 * @param file
	 *            File实例
	 * @return long 单位为M
	 * @throws Exception
	 */
	public long getFolderSize(java.io.File file) throws Exception {
		long size = 0;
		java.io.File[] fileList = file.listFiles();
		for (int i = 0; i < fileList.length; i++) {
			if (fileList[i].isDirectory()) {
				size = size + getFolderSize(fileList[i]);
			} else {
				size = size + fileList[i].length();
			}
		}
		return size;
	}

	/**
	 * 文件大小单位转换
	 * 
	 * @param size
	 * @return
	 */
	public String setFileSize(long size) {
		DecimalFormat df = new DecimalFormat("###.##");
		float f = ((float) size / (float) (1024 * 1024));

		if (f < 1.0) {
			float f2 = ((float) size / (float) (1024));

			return df.format(new Float(f2).doubleValue()) + "KB";

		} else {
			return df.format(new Float(f).doubleValue()) + "M";
		}

	}

	/**
	 * 删除指定目录下文件及目录
	 * 
	 * @param deleteThisPath
	 * @param filepath
	 * @return
	 */
	public void deleteFolderFile(String filePath, boolean deleteThisPath)
			throws IOException {
		if (!TextUtils.isEmpty(filePath)) {
			File file = new File(filePath);

			if (file.isDirectory()) {// 处理目录
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFolderFile(files[i].getAbsolutePath(), true);
				}
			}
			if (deleteThisPath) {
				if (!file.isDirectory()) {// 如果是文件，删除
					file.delete();
				} else {// 目录
					if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
						file.delete();
					}
				}
			}
		}
	}
}
